﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Infrastructure.Security.Rsa
{
    /// <summary>
    /// rsa加密
    /// </summary>
    public class RsaHelper
    {
        #region RSA 加密解密

        #region RSA 的密钥产生

        /// <summary>
        /// RSA产生密钥
        /// </summary>
        /// <param name="xmlKeys">私钥</param>
        /// <param name="xmlPublicKey">公钥</param>
        public void RsaKey(out string xmlKeys, out string xmlPublicKey)
        {
            var rsa = new RSACryptoServiceProvider();
            xmlKeys = rsa.ToXmlString(true);
            xmlPublicKey = rsa.ToXmlString(false);
        }

        #endregion RSA 的密钥产生

        #region RSA加密函数

        //##############################################################################
        //RSA 方式加密
        //KEY必须是XML的形式,返回的是字符串
        //该加密方式有长度限制的！
        //##############################################################################

        /// <summary>
        /// RSA的加密函数
        /// </summary>
        /// <param name="xmlPublicKey">公钥</param>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public string RsaEncrypt(string xmlPublicKey, string encryptString)
        {

            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPublicKey);
            var plainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString);
            var cypherTextBArray = rsa.Encrypt(plainTextBArray, false);
            return Convert.ToBase64String(cypherTextBArray);
        }

        /// <summary>
        /// RSA的加密函数
        /// </summary>
        /// <param name="xmlPublicKey">公钥</param>
        /// <param name="encryptString">待加密的字节数组</param>
        /// <returns></returns>
        public string RsaEncrypt(string xmlPublicKey, byte[] encryptString)
        {
            try
            {
                var rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPublicKey);
                var cypherTextBArray = rsa.Encrypt(encryptString, false);
                return Convert.ToBase64String(cypherTextBArray);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion RSA加密函数

        #region RSA的解密函数

        /// <summary>
        /// RSA的解密函数
        /// </summary>
        /// <param name="xmlPrivateKey">私钥</param>
        /// <param name="decryptString">待解密的字符串</param>
        /// <returns></returns>
        public string RsaDecrypt(string xmlPrivateKey, string decryptString)
        {
            try
            {

                var rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                var plainTextBArray = Convert.FromBase64String(decryptString);
                var dypherTextBArray = rsa.Decrypt(plainTextBArray, false);
                return (new UnicodeEncoding()).GetString(dypherTextBArray);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA的解密函数
        /// </summary>
        /// <param name="xmlPrivateKey">私钥</param>
        /// <param name="decryptString">待解密的字节数组</param>
        /// <returns></returns>
        public string RsaDecrypt(string xmlPrivateKey, byte[] decryptString)
        {
            try
            {

                var rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                var dypherTextBArray = rsa.Decrypt(decryptString, false);
                return (new UnicodeEncoding()).GetString(dypherTextBArray);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion RSA的解密函数

        #endregion RSA 加密解密

        #region RSA数字签名

        #region 获取Hash描述表

        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="strSource">待签名的字符串</param>
        /// <param name="hashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(string strSource, ref byte[] hashData)
        {
            try
            {
                var md5 = HashAlgorithm.Create("MD5");
                var buffer = Encoding.GetEncoding("GB2312").GetBytes(strSource);
                if (md5 != null) hashData = md5.ComputeHash(buffer);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="strSource">待签名的字符串</param>
        /// <param name="strHashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(string strSource, ref string strHashData)
        {
            try
            {
                //从字符串中取得Hash描述
                var md5 = HashAlgorithm.Create("MD5");
                var buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strSource);
                if (md5 != null)
                {
                    var hashData = md5.ComputeHash(buffer);
                    strHashData = Convert.ToBase64String(hashData);
                }

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="objFile">待签名的文件</param>
        /// <param name="hashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(System.IO.FileStream objFile, ref byte[] hashData)
        {
            try
            {
                //从文件中取得Hash描述
                var md5 = HashAlgorithm.Create("MD5");
                if (md5 != null) hashData = md5.ComputeHash(objFile);
                objFile.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取Hash描述表
        /// </summary>
        /// <param name="objFile">待签名的文件</param>
        /// <param name="strHashData">Hash描述</param>
        /// <returns></returns>
        public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
        {

            //从文件中取得Hash描述
            var md5 = HashAlgorithm.Create("MD5");
            if (md5 != null)
            {
                var hashData = md5.ComputeHash(objFile);
                objFile.Close();
                strHashData = Convert.ToBase64String(hashData);
            }

            return true;

        }

        #endregion 获取Hash描述表

        #region RSA签名

        /// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="strKeyPrivate">私钥</param>
        /// <param name="hashbyteSignature">待签名Hash描述</param>
        /// <param name="encryptedSignatureData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, byte[] hashbyteSignature, ref byte[] encryptedSignatureData)
        {
            var rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(strKeyPrivate);
            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
            //设置签名的算法为MD5
            rsaFormatter.SetHashAlgorithm("MD5");
            //执行签名
            encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);
            return true;

        }

        /// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="strKeyPrivate">私钥</param>
        /// <param name="hashbyteSignature">待签名Hash描述</param>
        /// <param name="strEncryptedSignatureData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, byte[] hashbyteSignature, ref string strEncryptedSignatureData)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(strKeyPrivate);
            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
            //设置签名的算法为MD5
            rsaFormatter.SetHashAlgorithm("MD5");
            //执行签名
            var encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);
            strEncryptedSignatureData = Convert.ToBase64String(encryptedSignatureData);
            return true;
        }

        /// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="strKeyPrivate">私钥</param>
        /// <param name="strHashbyteSignature">待签名Hash描述</param>
        /// <param name="encryptedSignatureData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, string strHashbyteSignature, ref byte[] encryptedSignatureData)
        {

            var hashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
            var rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(strKeyPrivate);
            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
            //设置签名的算法为MD5
            rsaFormatter.SetHashAlgorithm("MD5");
            //执行签名
            encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);

            return true;
        }

        /// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="strKeyPrivate">私钥</param>
        /// <param name="strHashbyteSignature">待签名Hash描述</param>
        /// <param name="strEncryptedSignatureData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureFormatter(string strKeyPrivate, string strHashbyteSignature, ref string strEncryptedSignatureData)
        {

            var hashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(strKeyPrivate);
            var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
            //设置签名的算法为MD5
            rsaFormatter.SetHashAlgorithm("MD5");
            //执行签名
            var encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);
            strEncryptedSignatureData = Convert.ToBase64String(encryptedSignatureData);
            return true;

        }

        #endregion RSA签名

        #region RSA 签名验证

        /// <summary>
        /// RSA签名验证
        /// </summary>
        /// <param name="strKeyPublic">公钥</param>
        /// <param name="hashbyteDeformatter">Hash描述</param>
        /// <param name="deformatterData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, byte[] hashbyteDeformatter, byte[] deformatterData)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPublic);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的时候HASH算法为MD5
                RSADeformatter.SetHashAlgorithm("MD5");
                if (RSADeformatter.VerifySignature(hashbyteDeformatter, deformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA签名验证
        /// </summary>
        /// <param name="strKeyPublic">公钥</param>
        /// <param name="strHashbyteDeformatter">Hash描述</param>
        /// <param name="deformatterData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, string strHashbyteDeformatter, byte[] deformatterData)
        {
            try
            {
                byte[] HashbyteDeformatter;
                HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
                RSA.FromXmlString(strKeyPublic);
                System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
                //指定解密的时候HASH算法为MD5
                RSADeformatter.SetHashAlgorithm("MD5");
                if (RSADeformatter.VerifySignature(HashbyteDeformatter, deformatterData))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA签名验证
        /// </summary>
        /// <param name="strKeyPublic">公钥</param>
        /// <param name="hashbyteDeformatter">Hash描述</param>
        /// <param name="strDeformatterData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, byte[] hashbyteDeformatter, string strDeformatterData)
        {
            try
            {
                var rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(strKeyPublic);
                var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                //指定解密的时候HASH算法为MD5
                rsaDeformatter.SetHashAlgorithm("MD5");
                var deformatterData = Convert.FromBase64String(strDeformatterData);
                if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData))
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA签名验证
        /// </summary>
        /// <param name="strKeyPublic">公钥</param>
        /// <param name="strHashbyteDeformatter">Hash描述</param>
        /// <param name="strDeformatterData">签名后的结果</param>
        /// <returns></returns>
        public bool SignatureDeformatter(string strKeyPublic, string strHashbyteDeformatter, string strDeformatterData)
        {
            try
            {
                var hashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter);
                var rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(strKeyPublic);
                var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                //指定解密的时候HASH算法为MD5
                rsaDeformatter.SetHashAlgorithm("MD5");
                var deformatterData = Convert.FromBase64String(strDeformatterData);
                if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData))
                {
                    return true;
                }

                return false;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion RSA 签名验证

        #endregion RSA数字签名
    }
}